package api

import (
	"net/http"

	"example.com/example/dao"
	"example.com/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configMachineRouter(router *httprouter.Router) {
	router.GET("/machine", GetAllMachine)
	router.POST("/machine", AddMachine)
	router.GET("/machine/:argId", GetMachine)
	router.PUT("/machine/:argId", UpdateMachine)
	router.DELETE("/machine/:argId", DeleteMachine)
}

func configGinMachineRouter(router gin.IRoutes) {
	router.GET("/machine", ConverHttprouterToGin(GetAllMachine))
	router.POST("/machine", ConverHttprouterToGin(AddMachine))
	router.GET("/machine/:argId", ConverHttprouterToGin(GetMachine))
	router.PUT("/machine/:argId", ConverHttprouterToGin(UpdateMachine))
	router.DELETE("/machine/:argId", ConverHttprouterToGin(DeleteMachine))
}

// GetAllMachine is a function to get a slice of record(s) from machine table in the custom_process database
// @Summary Get list of Machine
// @Tags Machine
// @Description GetAllMachine is a handler to get a slice of record(s) from machine table in the custom_process database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.Machine}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /machine [get]
// http "http://localhost:8080/machine?page=0&pagesize=20" X-Api-User:user123
func GetAllMachine(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "machine", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllMachine(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetMachine is a function to get a single record from the machine table in the custom_process database
// @Summary Get record from table Machine by  argId
// @Tags Machine
// @ID argId
// @Description GetMachine is a function to get a single record from the machine table in the custom_process database
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 200 {object} model.Machine
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /machine/{argId} [get]
// http "http://localhost:8080/machine/1" X-Api-User:user123
func GetMachine(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "machine", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetMachine(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddMachine add to add a single record to machine table in the custom_process database
// @Summary Add an record to machine table
// @Description add to add a single record to machine table in the custom_process database
// @Tags Machine
// @Accept  json
// @Produce  json
// @Param Machine body model.Machine true "Add Machine"
// @Success 200 {object} model.Machine
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /machine [post]
// echo '{"id": 11,"name": "ujsNcuCeCQyZCnKpgiwEkXGbB","create_time": "2180-12-21T18:56:32.559184649+08:00","update_time": "2287-04-30T13:24:30.126013213+08:00"}' | http POST "http://localhost:8080/machine" X-Api-User:user123
func AddMachine(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	machine := &model.Machine{}

	if err := readJSON(r, machine); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := machine.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	machine.Prepare()

	if err := machine.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "machine", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	machine, _, err = dao.AddMachine(ctx, machine)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, machine)
}

// UpdateMachine Update a single record from machine table in the custom_process database
// @Summary Update an record in table machine
// @Description Update a single record from machine table in the custom_process database
// @Tags Machine
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Param  Machine body model.Machine true "Update Machine record"
// @Success 200 {object} model.Machine
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /machine/{argId} [put]
// echo '{"id": 11,"name": "ujsNcuCeCQyZCnKpgiwEkXGbB","create_time": "2180-12-21T18:56:32.559184649+08:00","update_time": "2287-04-30T13:24:30.126013213+08:00"}' | http PUT "http://localhost:8080/machine/1"  X-Api-User:user123
func UpdateMachine(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	machine := &model.Machine{}
	if err := readJSON(r, machine); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := machine.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	machine.Prepare()

	if err := machine.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "machine", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	machine, _, err = dao.UpdateMachine(ctx,
		argId,
		machine)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, machine)
}

// DeleteMachine Delete a single record from machine table in the custom_process database
// @Summary Delete a record from machine
// @Description Delete a single record from machine table in the custom_process database
// @Tags Machine
// @Accept  json
// @Produce  json
// @Param  argId path int64 true "id"
// @Success 204 {object} model.Machine
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /machine/{argId} [delete]
// http DELETE "http://localhost:8080/machine/1" X-Api-User:user123
func DeleteMachine(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseUint64(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "machine", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeleteMachine(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
